package com.vchello.util;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.vchello.contants.CONTANTS;

/**
 * 发送邮件的方法
 * 
 * @author
 *
 */
@SuppressWarnings("static-access")
public class SendEmail extends Authenticator {

	private static Properties proper = null;
	private static Session session = null;
	/***************** 发送邮件服务器的地址、用户名、密码 ******************************/
	private static String smtp = "smtp.qq.com";

	private static ReadPropertyUtil readProperty = ReadPropertyUtil.getInstance();
	private static String adminEmail = "";
	private static String emailpass = "";

	private static String[] managerEmail = null;
	private static String[] notifySignupEmail = null;
	private static String[] notifyInvestorEmail = null;

	// 2017年1月11日重新编辑专题的通知邮箱
	private static String email1 = null;
	private static String email2 = null;
	private static String email3 = null;
	private static String email4 = null;
	private static String email5 = null;

	static {
		adminEmail = readProperty.getProperty("adminEmail", "vchello@vchello.com");
		emailpass = readProperty.getProperty("emailpass", "Yuzhangdeng0421");
		managerEmail = readProperty.getProperty("managerEmail", "chengyusan@vchello.com").split(";");
		notifySignupEmail = readProperty.getProperty("notifySignupEmail", "chengyusan@vchello.com").split(";");
		notifyInvestorEmail = readProperty.getProperty("notifyInvestorEmail", "chengyusan@vchello.com").split(";");
		// 2017年1月11日重新编辑专题的通知邮箱
		email1 = readProperty.getProperty("email1", "chengyusan@vchello.com");
		email2 = readProperty.getProperty("email2", "chengyusan@vchello.com");
		email3 = readProperty.getProperty("email3", "chengyusan@vchello.com");
		email4 = readProperty.getProperty("email4", "chengyusan@vchello.com");
		email5 = readProperty.getProperty("email5", "chengyusan@vchello.com");
	}

	private Address fromAddress = null;
	private static SendEmail sendEmail = null;
	private static Logger logger = Logger.getLogger(SendEmail.class);

	public SendEmail() {
	}

	public PasswordAuthentication getPasswordAuthentication() {
		return new PasswordAuthentication(adminEmail, emailpass);
	}

	public static SendEmail getInstance() {
		Object obj = null;
		if (sendEmail == null) {
			obj = "obj";
			synchronized (obj) {
				if (sendEmail == null) {
					sendEmail = new SendEmail();
				}
			}
		}
		return sendEmail;
	}

	public synchronized void setProperties() throws AddressException, UnsupportedEncodingException {
		if (proper == null) {
			fromAddress = new InternetAddress(adminEmail, "VCHello", "UTF-8");
			proper = new Properties();
			proper.put("mail.smtp.host", smtp);// 邮件服务器IP地址
			proper.put("mail.smtp.auth", "true");
			// proper.put("mail.smtp.port", "465");
			// proper.put("mail.smtp.socketFactory.class",
			// "javax.net.ssl.SSLSocketFactory");
			// proper.put("mail.smtp.socketFactory.fallback", "false");
			// proper.put("mail.smtp.socketFactory.port", "465");
			session = Session.getInstance(proper, this);
		}
	}

	/**
	 * 发送邮件
	 * 
	 * @param addresses
	 *            邮件地址数组形式
	 * @param subject
	 *            邮件标题
	 * @param message
	 *            邮件内容
	 * @throws AddressException
	 * @throws UnsupportedEncodingException
	 */
	public boolean sendMessage(String[] addresses, String subject, String message, String filePath)
			throws AddressException, UnsupportedEncodingException {
		// 添加附件
		if (StringUtils.isNotBlank(filePath)) {
			return sendAffixEmail(addresses, subject, message, filePath);
		} else {
			synchronized (SendEmail.class) {
				if (proper == null) {
					setProperties();
				}
				if (session == null)
					setProperties();
				MimeMessage sendObject = new MimeMessage(session);
				Address[] tempAddress = new Address[addresses.length];
				try {
					for (int i = 0; i < addresses.length; i++) {
						tempAddress[i] = new InternetAddress(addresses[i]);
					}

					sendObject.setFrom(fromAddress);
					sendObject.addRecipients(Message.RecipientType.TO, tempAddress);
					sendObject.setSubject(subject, "UTF-8");
					sendObject.setDataHandler(new DataHandler(message, "text/html;charset=UTF-8"));
					// Transport.send(sendObject);

					Transport.send(sendObject);
					proper = null;
					return true;
				} catch (Exception ex) {
					System.out.println("Sorry,send email error!" + ex.toString());
					ex.printStackTrace();
					return false;

				}
			}
		}
	}

	/**
	 * 发送带附件的邮件
	 * 
	 * @param host
	 * @param user
	 * @param pwd
	 */
	public boolean sendAffixEmail(String[] addresses, String subject, String message, String filePath) {
		synchronized (SendEmail.class) {
			try {
				// 设置发送邮件的邮件服务器的属
				if (proper == null) {
					setProperties();
				}
				Properties props = proper;
				// 用刚刚设置好的props对象构建一个session
				Session session = Session.getDefaultInstance(props);
				// 有了这句便可以在发送邮件的过程中在console处显示过程信息，供调试使
				// 用（你可以在控制台（console)上看到发送邮件的过程）
				// session.setDebug(true);
				// 用session为参数定义消息对象
				MimeMessage sendObj = new MimeMessage(session);

				// 加载发件人地址
				sendObj.setFrom(new InternetAddress(adminEmail));
				// 加载收件人地址
				Address[] tempAddress = new Address[addresses.length];
				for (int i = 0; i < addresses.length; i++) {
					tempAddress[i] = new InternetAddress(addresses[i]);
				}
				sendObj.addRecipients(Message.RecipientType.TO, tempAddress);
				// 加载标题
				// sendObj.setSubject(new
				// String(subject.getBytes("ISO-8859-1"),"UTF-8"));
				sendObj.setSubject(subject, "UTF-8");
				// 向multipart对象中添加邮件的各个部分内容，包括文本内容和附件
				Multipart multipart = new MimeMultipart();
				// 设置邮件的文本内容
				BodyPart contentPart = new MimeBodyPart();
				contentPart.setDataHandler(new DataHandler(message, "text/html;charset=UTF-8"));
				multipart.addBodyPart(contentPart);
				// 添加附件
				BodyPart messageBodyPart = new MimeBodyPart();

				DataSource source = new FileDataSource(filePath);
				// 添加附件的内容
				messageBodyPart.setDataHandler(new DataHandler(source));
				// 添加附件的标题

				// 设置文件名
				String filename = MimeUtility.encodeText(source.getName());
				messageBodyPart.setFileName(filename);
				multipart.addBodyPart(messageBodyPart);

				// 将multipart对象放到message中
				sendObj.setContent(multipart);
				// 保存邮件
				sendObj.saveChanges();
				// 发送邮件
				Transport transport = session.getTransport("smtp");
				// 连接服务器的邮箱
				transport.connect(smtp, adminEmail, emailpass);
				// 把邮件发送出去
				transport.sendMessage(sendObj, sendObj.getAllRecipients());
				transport.close();
				return true;
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}
		}
	}

	public static void sendEmail(String[] addresses, String subject, String message) {
		try {
			ThreadPool.sendEmail(addresses, subject, message, null);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			logger.error(e);
		}

	}

	private static String getAhref(String path) {
		// TODO Auto-generated method stub
		String s = "<a href=\"" + path + "\">" + path + "</a>";
		return s;
	}
	
	public static void sendInvitation(String email, String invitationName, String code){
		StringBuffer sb = new StringBuffer();
		sb.append("欢迎使用微投管理工具").append(invitationName).append("邀请您加入").append("<br/>");
		sb.append("请点击以下按钮进行身份确认，确认后您将成为").append(invitationName).append("的重要一员。").append("<br/>");
		sb.append("邀请码：").append(code);
		sb.append("<a href=\"" + CONTANTS.PATH + "/login?code=" + code
				+ "\">激活账号</a>");
		sb.append("<p>如果无法直接点击，请copy以下网址到浏览器进行激活：</p>");
		sb.append(CONTANTS.PATH + "/login?code=" + code);
		sendEmail(new String[]{email}, "邀请成员", sb.toString());
	}
	
	public static void sendEmailCode(String email, String code){
		StringBuffer sb = new StringBuffer();
		sb.append("您的邮箱验证码是：").append(code);
		sendEmail(new String[] {email}, "邮箱验证码", sb.toString());
	}
}